package com.david.reader.adapter

import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.david.reader.R
import com.david.reader.bean.BookBean

class BookShellAdapter : RecyclerView.Adapter<BookShellAdapter.BookShellHolder>(),
    View.OnClickListener, View.OnLongClickListener {
    var datas: ArrayList<BookBean> = ArrayList()

    var onBookItemClickListener: OnBookItemClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookShellHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_book_shell, parent, false)
        view.setOnClickListener(this@BookShellAdapter)
        view.setOnLongClickListener(this@BookShellAdapter)
        return BookShellHolder(view)
    }

    override fun onBindViewHolder(holder: BookShellHolder, position: Int) {
        holder.name.text = Uri.decode(datas[position].simpleName)
        holder.type.text = if (datas[position].type == 0) "TXT" else "PDF"

        holder.progress.text = String.format("%d/%d", datas[position].currentPage, datas[position].pageCount)

        holder.itemView.tag = position
    }

    override fun getItemCount(): Int {
        return datas.size
    }

    class BookShellHolder(item: View) : RecyclerView.ViewHolder(item) {
        var type: TextView = item.findViewById(R.id.item_book_shell_type)
        var name: TextView = item.findViewById(R.id.item_book_shell_name)
        var progress: TextView = item.findViewById(R.id.item_book_shell_progress)
    }

    override fun onClick(v: View?) {
        v?.let {
            if (it.tag is Int) {
                val position = it.tag as Int
                onBookItemClickListener?.onBookItemClick(position, datas[position])
            }
        }
    }

    override fun onLongClick(v: View?): Boolean {
        v?.let {
            if (it.tag is Int) {
                val position = it.tag as Int
                onBookItemClickListener?.onBookItemLongClick(position, datas[position])
            }
        }
        return true
    }
}

interface OnBookItemClickListener{
    fun onBookItemClick(position: Int, bookBean: BookBean)
    fun onBookItemLongClick(position: Int, bookBean: BookBean)
}